//
//  HPlayListView.m
//  HMusicPlayer
//
//  Created by Hament on 14/9/16.
//  Copyright (c) 2014年 HJ. All rights reserved.
//

#import "HPlayListView.h"
#import "HGroup.h"
#import "HPlaylistItem.h"
#import "HSongItem.h"
#import "HPlayListGroupCell.h"
#import "HCoreConfig.h"
#import "HskinManager.h"
#import "HHLTableRowView.h"
#import "HMainWC.h"
#import "HSongListView.h"
#import "HSQLManager.h"
#import "TagReader.h"
#import "HGroupListView.h"
#import "HJAudioPlayer.h"
#import "HTriangleView.h"

#import <OrigamiEngine/ORGMEngine.h>
#import "DOUAudioStreamer.h"

@interface HPlayListView ()


@property (nonatomic) BOOL isFocusPlayListView;
@property (nonatomic,strong) NSTextField * calTf;//用来计算行高的

@end


@implementation HPlayListView

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
    }
    return self;
}

- (void)drawRect:(NSRect)dirtyRect
{
    [super drawRect:dirtyRect];
    
    // Drawing code here.
    
    if (self.isFocusPlayListView) {
        CGContextRef ctx = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
        CGContextSaveGState(ctx);
        NSBezierPath *path = [NSBezierPath bezierPathWithRect:NSMakeRect(0, 0, dirtyRect.size.width-5, dirtyRect.size.height-2)];
        [path setLineWidth:2];
        [[NSColor selectedTextBackgroundColor] set];
        [path stroke];
        CGContextRestoreGState(ctx);
        
    }

    
}




-(void)awakeFromNib {

    
    //三角形,正在播放标识符
    self.triangleView=[[HTriangleView alloc] initWithFrame:NSMakeRect(5, 20, 10, 10)];
//    [self.calTf setAutoresizingMask:(NSViewMinYMargin|NSViewMaxXMargin)];
    
    //用于计算行高
    self.calTf=[[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 106, 20)];
    self.calTf.font=[NSFont systemFontOfSize:12];
    [self.calTf.cell setAlignment:NSLeftTextAlignment];
    [[self.calTf cell] setBordered:NO];
    [[self.calTf cell] setLineBreakMode:NSLineBreakByWordWrapping];
     //[self.calTf setAutoresizingMask:(NSViewMinYMargin|NSViewMaxYMargin|NSViewMaxXMargin|NSViewMinXMargin|NSViewHeightSizable)];
    [[self.calTf cell] setUsesSingleLineMode:NO];
    self.calTf.stringValue=@"";
    
    
    /*注册允许拖放的类型*/
     self.supportDragTypesArr=@[HSONGITEMTYPE,(id)kUTTypeURL];
    [self.tableV registerForDraggedTypes:self.supportDragTypesArr];
    [self.tableV setDraggingSourceOperationMask:NSDragOperationGeneric forLocal:NO];//是否只局限于本地拖放
    
    
    //设置右击menu
    [self.tableV setMenu:self.pTableMenu];
    
    //设置双击
    [self.tableV setDoubleAction:@selector(tableDoubleClick:)];
    
    //上半分组的datasource
    [self prepareTopDatasource];
    
    //所有数据
    [self reloadDataSource];
    
    //[self addSubview:self.calTf];
    

}



#pragma mark  ---------- lazylaoding--------

-(NSMutableArray *)dataSource {


    if (!_dataSource) {
        _dataSource=[[NSMutableArray alloc] init];
    }
    return _dataSource;
}


-(NSMenu*)pTableMenu{

    if (!_pTableMenu) {
        _pTableMenu=[[NSMenu alloc] init];
        [_pTableMenu setAutoenablesItems:YES];
        _pTableMenu.delegate=self;
        [_pTableMenu addItemWithTitle:NSLocalizedString(@"delete", nil) action:@selector(deleteCertainPlaylist) keyEquivalent:@""];

    }


    return _pTableMenu;
}


#pragma mark  ---------- 业务逻辑--------

#pragma mark -------数据源处理

#pragma mark 获取top分组等数据源
-(void)prepareTopDatasource{


    //top分组
    HGroup * g1=[[HGroup alloc] init];
    g1.title=NSLocalizedString(@"Top", nil);
    g1.identifier=@"top";
    
    HPlaylistItem * pi1=[HPlaylistItem defaultItem];
    pi1.syncid=itunesSyncid;
    pi1.name=NSLocalizedString(@"itunes", nil);
    
    /*
    HPlaylistItem * pi2=[HPlaylistItem defaultItem];
    pi2.syncid=onlineSyncid;
    pi2.name=NSLocalizedString(@"online", nil);
    */
    
    
    HPlaylistItem * pi3=[HPlaylistItem defaultItem];
    pi3.syncid=likeSyncid;
    pi3.name=NSLocalizedString(@"favourite", nil);
    

    //播放列表分组
    
    HGroup * g2=[[HGroup alloc] init];
    g2.title=NSLocalizedString(@"Playlist", nil);
    g2.identifier=@"playlist";
    
    self.topGroupArr=@[g1,pi1,pi3,g2];


}


#pragma mark刷新数据源
-(void)reloadDataSource{

 
    
 [self.dataSource removeAllObjects];
 //1.添加第一part
 [self.dataSource addObjectsFromArray:self.topGroupArr];
    
 //2.添加播放列表
    self.plistDataSource=[HSQLManager getPlayListFromSongDB];
    [self.dataSource addObjectsFromArray:self.plistDataSource];

    [self.tableV reloadData];
}





#pragma mark添加播放符号
-(void)addThePlaySymbol{

    //刷新播放符
    NSInteger selectrow=[self.tableV selectedRow];
    if(selectrow!=-1) {
        NSTableCellView * cellview=[[HMainWC shareWc].playListView.tableV viewAtColumn:0 row:selectrow makeIfNecessary:YES];
        self.triangleView.frame=NSMakeRect(3, cellview.frame.size.height-18, 10, 10);
        [cellview addSubview:self.triangleView];
        
    }
}


#pragma mark ----click new playlist button
-(void)addNewPlaylist{

    
     HPlaylistItem * pitem=[HPlaylistItem defaultItem];
    NSString * defaultname=NSLocalizedString(@"new play list", nil);
    pitem.name=[self getPlayplstNameWithdefaultName:defaultname andIndex:0];
    
     [HSQLManager insertPlaylist:pitem songs:nil];
     [[HSQLManager shareSqlMg] closeSongDB];

    //1.先滚到最后
    NSUInteger row =[self.dataSource count]-1;
    [self.tableV scrollRowToVisible:row];
    
    //2.再插入动画

    [self.dataSource addObject:pitem];
    [self.plistDataSource addObject:pitem];
    
    row =[self.dataSource count]-1;
    
    [self.tableV insertRowsAtIndexes:[NSIndexSet indexSetWithIndex:row] withAnimation:NSTableViewAnimationSlideLeft];
    
    
    //导入后刷新定位播放列表,选中时再高亮会有问题,所以延时刷新
    [self performSelector:@selector(locationRowAfterimport) withObject:nil afterDelay:0.1];

}



#pragma mark ----获取playlist名字是否能用

-(NSString*)getPlayplstNameWithdefaultName:(NSString*)theName andIndex:(NSUInteger)beginIndex{

    
    //debugLog(@"111111111");
    if (self.plistDataSource.count==0) {
        return theName;
    }
    
    BOOL findSame=NO;
    for (HPlaylistItem * pitem in self.plistDataSource) {
        if([pitem.name isEqualToString:theName]) {
            findSame=YES;
            break ;
        }
    }
    
    if (findSame==YES) {
        NSUInteger nextIndex=beginIndex+1;
        NSString * nextname=[NSString stringWithFormat:@"%@%d",NSLocalizedString(@"new play list", nil),nextIndex];
      return  [self getPlayplstNameWithdefaultName:nextname andIndex:nextIndex];
    } else {
        return theName;
    }
    
    return theName;
}





#pragma mark ----双击
-(void)tableDoubleClick:(id)object{


    NSInteger clickrow=[self.tableV clickedRow];

    if (clickrow!=-1) {
    
        //如果是第一组的,不用理会
        if(clickrow<=(self.topGroupArr.count-1)) {return;}
        
        [[self window] endEditingFor:nil];
        NSTableCellView * cell=[self.tableV viewAtColumn:0 row:clickrow makeIfNecessary:YES];
        
        [self.window makeFirstResponder:cell.textField];
        [cell.textField selectText:self];
        
        
    
    }

}

#pragma mark 删除playlist
-(void)deleteCertainPlaylist{


    NSUInteger clickrow= [self.tableV clickedRow];

    NSUInteger pindex=clickrow-self.topGroupArr.count;
    
     HPlaylistItem * pitem=[self.dataSource objectAtIndex:clickrow];
    
    
    //如果删除的正式当前播放的列表
    if ([pitem.syncid isEqualToString:[HJAudioPlayer sharePlayer].playListID]) {

        [[HJAudioPlayer sharePlayer] emptyCurrentPlayQueue];
        [[HMainWC shareWc] resetPlayplaneUIWithSongItem:nil];
        
    }
    
    
    
     BOOL res= [HSQLManager deletePlaylistWithItem:pitem];
    
    if (res) {

        
        //[self.tableV beginUpdates];
        [self.dataSource removeObjectAtIndex:clickrow];
        [self.plistDataSource removeObjectAtIndex:pindex];
        [self.tableV removeRowsAtIndexes:[NSIndexSet indexSetWithIndex:clickrow] withAnimation:NSTableViewAnimationSlideRight];
        //[self.tableV endUpdates];
        
        
    }


    
    //debugLog(@"plistDataSource count:%d",self.plistDataSource.count);
}


#pragma mark 重命名(已经没用,和双击命名混用会引起问题)
-(void)renameCertainPlaylist{

    NSUInteger clickrow= [self.tableV clickedRow];
    //当点击空白行时
    
    if(clickrow!=-1) {
        NSTableCellView * cell=[self.tableV viewAtColumn:0 row:clickrow makeIfNecessary:YES];
    [[self window] endEditingFor:nil];
        
        [self.window makeFirstResponder:cell.textField];
        [cell.textField selectText:self];
    
    }

}





#pragma mark //处理拖拽文件夹创建playlist
-(void)createPlaylistWithFolderPath:(NSURL*)foUrl handelCount:(int *)handelCount{

    
    NSString * fopath=foUrl.path;
    
    
    
    NSString * foldername=[fopath lastPathComponent];//folder name

    
    
    HPlaylistItem * pitem=[HPlaylistItem defaultItem];
    pitem.name=foldername;
    pitem.folderPath=fopath;
    
    

    NSMutableArray * songsArr=[NSMutableArray arrayWithCapacity:10];
    
    NSFileManager * fileManager=[NSFileManager defaultManager];
     NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
   // NSArray * filesArr = [fileManager contentsOfDirectoryAtPath:fopath error:nil];
    NSDirectoryEnumerator *enumerator=[fileManager enumeratorAtPath:fopath];
    
    NSString *file;
    //这种写法会检测documents下所有文件，效率低下
    	while (file = [enumerator nextObject]) {
              //NSLog(@"file:%@",[file description]);

            NSString * filepath=[fopath stringByAppendingPathComponent:file];
            NSURL * fileurl=[[NSURL alloc] initFileURLWithPath:filepath];
            NSString *typeIdentifier;

            [fileurl getResourceValue:&typeIdentifier forKey:NSURLTypeIdentifierKey error:NULL];
            if  ([workspace type:typeIdentifier conformsToType:@"public.audio"]){
//                 debugLog(@"audio filepath:%@",filepath);

                //如果能获取到duration,视为合法音乐格式
                [self gengrateHsongItemsWithUrl:fileurl filepath:filepath holdArr:&songsArr];
                
            }
            
            
    	}


    [HSQLManager insertPlaylist:pitem songs:songsArr];
    

}

//根据一堆外部文件生成hsongitem
-(void)gengrateHsongItemsWithUrl:(NSURL*)fileurl filepath:(NSString*)filepath holdArr:(NSMutableArray**)arr{

    @autoreleasepool {
        
   
    if (!filepath) {
        filepath=fileurl.path;
    }
    NSMutableArray * songsArr=*arr;


    //如果能获取到duration,视为合法音乐格式
    NSUInteger duration=[[HCoreConfig shareConfig] getSoundDuration:fileurl];
    if (duration!=InvalidSoundDuration) {
        
        
        TagReader *t = [[TagReader alloc] initWithFileAtPath:filepath];
        
        HSongItem * songItem=[[HSongItem alloc] init];
        
        //song localpath
        songItem.localPath=filepath;
        
        //song name
        if (t.title==nil) {

            NSString* filename = [[filepath lastPathComponent] stringByDeletingPathExtension];
            
            songItem.songName=filename;
            //debugLog(@"name:%@",songItem.songName);
        } else {
            songItem.songName=t.title;
        }
        
        //duration
        songItem.songDuration=duration;
        
        //song type
        songItem.songType=CHECKSTR(filepath.pathExtension);
        
        
        //artist
        songItem.album=CHECKSTR(t.album);
        
        //album
        songItem.artist=CHECKSTR(t.artist);
        
        //bookmark
        //创建score bookmark
        NSError * bookmarkerror=nil;
        NSData * data =[fileurl bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope
                                                includingResourceValuesForKeys:nil
                                                                 relativeToURL:nil
                                                                         error:&bookmarkerror];
        
       
        if (bookmarkerror) {
            debugLog(@"bookmarkerror:%@",bookmarkerror.description);
        } else {
            songItem.bookmark=data;
            
        }
        
        
        [songsArr addObject:songItem];
        
        
    }

 }

}



#pragma mark //插入到某个playlist
-(void)insertSongsToplaylist:(HPlaylistItem*)pitem dragInfo:(id<NSDraggingInfo>)info {

  __block NSMutableArray * songItemsArr=[NSMutableArray array];
    NSArray *classes = @[[HSongItem class]];
    
    //添加到某一播放列表
    [info enumerateDraggingItemsWithOptions:0 forView:self.tableV classes:classes searchOptions:nil usingBlock:^(NSDraggingItem *draggingItem, NSInteger idx, BOOL *stop) {
        HSongItem *songitem = draggingItem.item;
        [songItemsArr addObject:songitem];
        
    }];
    
    
    [HSQLManager batchInsertSongsWithPlaylist:pitem songs:songItemsArr db:[HSQLManager shareSqlMg].songDB];

}



#pragma mark //创建playlist,并插入拖放的歌曲
-(void)insertPlaylist:(HPlaylistItem*)pitem  dragInfo:(id<NSDraggingInfo>)info {
    
    __block NSMutableArray * songItemsArr=[NSMutableArray array];
    NSArray *classes = @[[HSongItem class]];
    
    //添加到某一播放列表
    [info enumerateDraggingItemsWithOptions:0 forView:self.tableV classes:classes searchOptions:nil usingBlock:^(NSDraggingItem *draggingItem, NSInteger idx, BOOL *stop) {
        HSongItem *songitem = draggingItem.item;
        [songItemsArr addObject:songitem];
         
    }];
    
    
    [HSQLManager insertPlaylist:pitem songs:songItemsArr];
    
    
}

#pragma mark 延时刷新,导入后刷新定位播放列表到最后一项------
-(void)locationRowAfterimport{
    
    [self performSelectorOnMainThread:@selector(locationRowAfterimportOnMainThead) withObject:nil waitUntilDone:NO];
    
}

-(void)locationRowAfterimportOnMainThead{
    
    //定位到最后一个播放列表
    if ([self.plistDataSource count]>0) {
        NSUInteger row =[self.dataSource count]-1;
        [self.tableV scrollRowToVisible:row];
        [self.tableV selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO];
    }
    
    
    [self displayTheFocusRingFrame:NO];//移除高亮框
    
    //移除loading
    [[HMainWC shareWc] removeGLoadingReminder];
}

#pragma mark 延时刷新,导入后刷新定位播放列表到指定行------
-(void)locationRowAfterimportWithRow:(NSString*)locateRow{
    

    [self performSelectorOnMainThread:@selector(locationRowOnimportOnMainThead:) withObject:locateRow waitUntilDone:NO];
    
}

-(void)locationRowOnimportOnMainThead:(NSString*)therow{
    
    NSUInteger row=therow.integerValue;
    
    //定位到最后一个播放列表
    if ([self.plistDataSource count]>0) {
//        NSUInteger row =[self.dataSource count]-1;
//        [self.tableV scrollRowToVisible:row];
        [self.tableV selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO];
    }
    
    
    [self displayTheFocusRingFrame:NO];//移除高亮框
    
    //移除loading
    [[HMainWC shareWc] removeGLoadingReminder];
}





#pragma mark drag显示高亮的框------
-(void)displayTheFocusRingFrame:(BOOL)flag{

    
    return; //此方法有bug,当从外面drag时,无法知道drag取消的动作

    self.isFocusPlayListView=flag;
    [self setNeedsDisplay:YES];

}

#pragma mark 获取当前选择的分类
-(HPlaylistItem*)getCurrentSelectPlaylistItem{

    NSUInteger selectrow=[self.tableV selectedRow];
    
    
    if (selectrow==-1) {
        return nil;
    }
    HPlaylistItem * pitem=[self.dataSource objectAtIndex:selectrow];
    return pitem;
}


#pragma mark 拖入类型限制,文件夹和音频文件
- (NSDictionary *)pasteboardReadingOptions {
    
    
    return @{NSPasteboardURLReadingFileURLsOnlyKey: @NO,
             NSPasteboardURLReadingContentsConformToTypesKey:@[HSONGITEMTYPE,(id)kUTTypeFolder]};//,@"public.audio"
}

- (BOOL)containsAcceptableURLsFromPasteboard:(NSPasteboard *)pasteboard {
    return [pasteboard canReadObjectForClasses:@[[HSongItem class],[NSURL class]]
                                       options:[self pasteboardReadingOptions]];
}

#pragma mark  ---------- tableview delegate (view based)--------

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView{
    
    
    return [self.dataSource count];
}


- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row{
    
    return [self.dataSource objectAtIndex:row];
    
}

// This method is optional if you use bindings to provide the data
- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
    
    // debugLog(@"loop row:%ld",row);

    HPlayListGroupCell *cellView;
    id entity = [self.dataSource objectAtIndex:row];
    
    //group
    if ([entity isKindOfClass:[HGroup class]]) {
        HGroup * thentity=(HGroup*)entity;
        cellView=[tableView makeViewWithIdentifier:@"groupCell" owner:nil];
        cellView.titleTf.stringValue=thentity.title;
        cellView.titleTf.textColor=[HCoreConfig shareConfig].currentSkinManager.leftListGroupCellTextolor;
        
        //play list should display add button
        if ([thentity.identifier isEqualTo:@"playlist"]) {
            
            [cellView.theBtn setImage:[HCoreConfig shareConfig].addPlaylistNorImg];
            [cellView.theBtn setAlternateImage:[HCoreConfig shareConfig].addPlaylistHltImg];
            
            [cellView.theBtn setTarget:self];
            [cellView.theBtn setAction:@selector(addNewPlaylist)];
            [cellView.theBtn setHidden:NO];
        } else {
             [cellView.theBtn setHidden:YES];
        }
        
        //由于cell会重用,所以需要处理
        NSView *view=[cellView viewWithTag:playTringleViewTag];
        if (view) {
            [view removeFromSuperview];
        }
 
        
    } else  {
        
        HPlaylistItem*  songentity =(HPlaylistItem*)entity;
        

           cellView=[tableView makeViewWithIdentifier:@"norCell" owner:tableView];
           cellView.textField.delegate=self;
           cellView.textField.stringValue=songentity.name;
           cellView.textField.textColor=[HCoreConfig shareConfig].currentSkinManager.leftListNormalCellTextColor;
        
        //只有 playlist可以更改
        NSString * syncid_m=songentity.syncid;
        if ([syncid_m isEqualToString:itunesSyncid ]||[syncid_m isEqualToString:onlineSyncid ] ||[syncid_m isEqualToString:likeSyncid ]  ) {
            [[cellView.textField cell] setEditable:NO];
            
        } else {
            
            [[cellView.textField cell] setEditable:YES];
        }
        
        
        //添加播放标示符
        if([[HJAudioPlayer sharePlayer].playListID isEqualToString:songentity.syncid]) {
            self.triangleView.frame=NSMakeRect(3, cellView.frame.size.height-16, 10, 10);
         [cellView addSubview:self.triangleView];
        } else {
        
            //由于cell会重用,所以需要处理
            NSView *view=[cellView viewWithTag:playTringleViewTag];
            
            if (view) {
                [view removeFromSuperview];
            }

        
        }
        
        
    }
    
    return cellView;
    
}

- (BOOL)tableView:(NSTableView *)tableView isGroupRow:(NSInteger)row{


    id entity = [self.dataSource objectAtIndex:row];
    BOOL isGroup= ([entity isKindOfClass:[HGroup class]]);

    return isGroup;
}


//rowview view-base下使用
- (NSTableRowView *)tableView:(NSTableView *)tableView rowViewForRow:(NSInteger)row {
    
    HHLTableRowView * rowView=[tableView makeViewWithIdentifier:NSTableViewRowViewKey owner:nil ];
    
    return rowView;
}


- (BOOL)tableView:(NSTableView *)tableView shouldSelectRow:(NSInteger)row{

    id entity = [self.dataSource objectAtIndex:row];
    BOOL select= [entity isKindOfClass:[HGroup class]]?NO:YES;


    return select;
}


///*
static  NSTableCellView * thecellView;
- (CGFloat)tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row{
    

        HPlaylistItem* entity = [self.dataSource objectAtIndex:row];
        
        
        
        if ([entity isKindOfClass:[HGroup class]]) {
        
        
            return 32;
        
        } else {
        

//        if(!thecellView){
//            thecellView=[tableView makeViewWithIdentifier:@"norCell2" owner:tableView];
//        }
//
//
//        thecellView.textField.stringValue=entity.name;
//        
//        CGFloat textWidth=thecellView.textField.frame.size.width;
//        CGFloat minHeight = [((NSTextFieldCell *)[thecellView.textField cell]) cellSizeForBounds:NSMakeRect(0, 0, textWidth, FLT_MAX)].height;
//        
//        return MAX(minHeight+8, 32);
            
        
          self.calTf.stringValue=entity.name;
          CGFloat textWidth=self.calTf.frame.size.width;
          CGFloat minHeight = [((NSTextFieldCell *)[self.calTf cell]) cellSizeForBounds:NSMakeRect(0, 0, textWidth, FLT_MAX)].height;
            
           // debugLog(@"minHeight:%f,textWidth:%f",minHeight,textWidth);
            
            return MAX(minHeight+8, 32);
    }
    

    
    return 60;
}

//*/


- (void)tableViewSelectionDidChange:(NSNotification *)notification {
    

    
    NSTableView * tableview=[notification object];
    
    
    //debugLog(@"se dd");

    
    /*
     NSIndexSet * selectindexset= [tableview selectedRowIndexes];
     //当点击空白行时
     if ([selectindexset count]==0) {
     //第几行第几列
     [tableview enumerateAvailableRowViewsUsingBlock:^(NSTableRowView *rowView, NSInteger row) {
     for (NSInteger column = 0; column < rowView.numberOfColumns; column++) {
     NSView *cellView = [rowView viewAtColumn:column];
     // Is this an NSTableCellView?
     if ([cellView isKindOfClass:[MacClientCell class]]) {
     MacClientCell *tableCellView = (MacClientCell *)cellView;
     // It is -- grab the text field and bold the font if selected
     NSTextField * nametextField = tableCellView.nameTf;
     NSTextField * companyxtField = tableCellView.companyTf;
     NSButton   * deleteBtn= tableCellView.deleteBtn;
     
     nametextField.textColor=[NSColor blackColor];
     companyxtField.textColor=[NSColor lightGrayColor];
     rowView.backgroundColor=[NSColor clearColor];
     [deleteBtn setHidden:YES];
     
     }
     }
     
     }];
     return;
     }
     
     
     // NSInteger theselectRow=[tableview selectedRow];
     // debugLog(@"selected row:%ld",theselectRow);
     
     */
    
    
    
    //如果之前有selectrow,删除row时会引起该方法触发,所以需要判断
    NSInteger theselectRow=[tableview selectedRow];
    if (theselectRow!=-1) {
        HPlaylistItem * pitem=[self.dataSource objectAtIndex:theselectRow];

         [[HMainWC shareWc].songListView reloadSonglistWithPlaylistItem:pitem];
        
        
        
    }
    //当没选中时,莫认选中第一
    else {
    
       [self.tableV selectRowIndexes:[NSIndexSet indexSetWithIndex:1] byExtendingSelection:NO];
    
    }

    
    [tableview enumerateAvailableRowViewsUsingBlock:^(NSTableRowView *rowView, NSInteger row) {
        

        
        //第几行第几列
        for (NSInteger column = 0; column < rowView.numberOfColumns; column++) {
            NSView *cellView = [rowView viewAtColumn:column];
            // Is this an NSTableCellView?
            
            if ([cellView isKindOfClass:[NSTableCellView class]]) {
                NSTableCellView *tableCellView = (NSTableCellView *)cellView;
                // It is -- grab the text field and bold the font if selected
                NSTextField * titleTf = tableCellView.textField;
                
                if (rowView.selected) {
                    
                    titleTf.textColor=[HCoreConfig shareConfig].currentSkinManager.rightListCellHighlightTextColor;
                    
                } else {
                    titleTf.textColor=[HCoreConfig shareConfig].currentSkinManager.leftListNormalCellTextColor;
                    
                    
                }
            }

        }
    }];
    
  
    


    
    
}




#pragma mark -----拖放有关的代理-----
//如果实现了该方法(tableView:writeRowsWithIndexes:toPasteboard:不会再调用),当tableview作为dragsource时,会把选中的行的实体类自动写入pasteboard
//- (id<NSPasteboardWriting>)tableView:(NSTableView *)tableView pasteboardWriterForRow:(NSInteger)row {
//    return self.dataSource[row];
//}




//1,这个方法只有拖拽源为tableview时才执行
- (void)tableView:(NSTableView *)tableView draggingSession:(NSDraggingSession *)session willBeginAtPoint:(NSPoint)screenPoint forRowIndexes:(NSIndexSet *)rowIndexes {
//    NSUInteger len = ([rowIndexes lastIndex]+1) - [rowIndexes firstIndex];
//    _objectRange = NSMakeRange([rowIndexes firstIndex], len);
//    _currentlyDraggedObjects = [self.datasource objectsAtIndexes:rowIndexes];
}


//拖放结束后
- (void)tableView:(NSTableView *)tableView draggingSession:(NSDraggingSession *)session endedAtPoint:(NSPoint)screenPoint operation:(NSDragOperation)operation {

    
    
    
}




// 2.确定拖拽的动作信息,该方法会随着拖放位置改变而执行
- (NSDragOperation)tableView:(NSTableView *)tableView validateDrop:(id<NSDraggingInfo>)info proposedRow:(NSInteger)row proposedDropOperation:(NSTableViewDropOperation)dropOperation {
   // NSLog(@"dropOperation:%lu",dropOperation);
    
    /*
     if (dropOperation == NSTableViewDropAbove && (_objectRange.location > row || _objectRange.location+_objectRange.length < row)) {
     if ([info draggingSource] == tableView) {
     //如果移动到外面
     if ([info draggingSourceOperationMask] == NSDragOperationCopy) {
     info.animatesToDestination = YES;
     return NSDragOperationCopy;
     }
     
     else {
     return NSDragOperationMove;
     }
     }
     //如果不是tableview作为拖动源,也就是说人家拖进来
     else {
     if ([self containsAcceptableURLsFromPasteboard:[info draggingPasteboard]]) {
     info.animatesToDestination = YES;
     return NSDragOperationCopy;
     }
     }
     }
     */
    NSDragOperation result=NSDragOperationCopy;
    if (row<=(self.dataSource.count-1)) {

     HPlaylistItem* entity = [self.dataSource objectAtIndex:row];
    
    //不允许拖放到group header
    if ([entity isKindOfClass:[HGroup class]]) {
         [self displayTheFocusRingFrame:NO];
        return NSDragOperationNone;
    }
    
    //debugLog(@"Htab:[info draggingSource]:%@",[info draggingSource]);
    
    
    

    
   
    
    id dragSource=[info draggingSource];//拖放源头
    
    //自己不允许拖放
    if (dragSource == self.tableV){
        [self displayTheFocusRingFrame:NO];
        return NSDragOperationNone;
        
    }
    //如果drag source为songlistView
    else if (dragSource ==[HMainWC shareWc].songListView.tableV) {
        
        
       
        if(dropOperation == NSTableViewDropAbove){
        
            //1.只允许拖放到最后的位置
            [self.tableV setDropRow:self.dataSource.count dropOperation:NSDragOperationGeneric];
            
            
            
        }
        else if(dropOperation == NSTableViewDropOn){
        
           
            
            //1.itunes,收藏,在线不允许拖放
            if ([entity isKindOfClass:[HPlaylistItem class]]) {
                
                if([entity.syncid isEqualToString:itunesSyncid] || [entity.syncid isEqualToString:likeSyncid] || [entity.syncid isEqualToString:onlineSyncid]){
                    [self displayTheFocusRingFrame:NO];
                    return NSDragOperationNone;
                    
                }
                
            }
            
            //2.需要检查拖放的歌曲如果已经是当前列表则不能拖放

            NSArray * arr=[info draggingPasteboard].pasteboardItems;

            NSPasteboardItem * firstPasteItem=arr[0];
            NSData * songitemdata=[firstPasteItem dataForType:HSONGITEMTYPE];
             HSongItem * songitem= (HSongItem*)[NSKeyedUnarchiver unarchiveObjectWithData:songitemdata];
           // debugLog(@"pasteboard:%p ,songitem name:%@ ,duration:%ld",[info draggingPasteboard],songitem.songName,(long)songitem.songDuration);
            if([songitem.playListSyncID isEqualToString:entity.syncid]) {
                
                [self displayTheFocusRingFrame:NO];
            return NSDragOperationNone;
            
            }
    
        
        }
  
        
    }
    //app 外部拖放
    else {
    
        
        
        debugLog(@"items count:%d",[[info draggingPasteboard] pasteboardItems].count);
        
        
        //1.只允许拖放到最后的位置
        if ([self containsAcceptableURLsFromPasteboard:[info draggingPasteboard]]) {
             [self.tableV setDropRow:self.dataSource.count dropOperation:NSDragOperationGeneric];

        } else {
            [self displayTheFocusRingFrame:NO];
        return NSDragOperationNone;
        }
  
    
    }
    
    }
    //如果拖到超过数据源的数量位置,统一拖放到最后
    else {
    
        if ([self containsAcceptableURLsFromPasteboard:[info draggingPasteboard]]) {
            [self.tableV setDropRow:self.dataSource.count dropOperation:NSDragOperationGeneric];

        } else {
[self displayTheFocusRingFrame:NO];
            return NSDragOperationNone;
        }
    }
    
    [self displayTheFocusRingFrame:YES];
    return result;
}




//该方法会update拖放的item信息 ,这里可以实时更新拖放item的显示cell布局,cell的位置
- (void)tableView:(NSTableView *)tableView updateDraggingItemsForDrag:(id<NSDraggingInfo>)draggingInfo {
    
    /*
     [draggingInfo enumerateDraggingItemsWithOptions:0 forView:tableView classes:classes searchOptions:nil usingBlock:^(NSDraggingItem *draggingItem, NSInteger idx, BOOL *stop) {
     if ([draggingItem.item isKindOfClass:[DesktopEntity class]]) {
     DesktopEntity *entity = (DesktopEntity *)draggingItem.item;
     draggingItem.draggingFrame = [tableCellView frame];
     draggingItem.imageComponentsProvider = ^NSArray *{
     if ([entity isKindOfClass:[DesktopImageEntity class]])
     [tableCellView.imageView setImage:[(DesktopImageEntity *)entity image]];
     [tableCellView.textField setStringValue:entity.name];
     return [tableCellView draggingImageComponents];
     };
     validCount++;
     } else {
     draggingItem.imageComponentsProvider = nil;
     }
     }];
     
     */
    
    //debugLog(@"11111");
    
}


//鼠标松手,落下操作
- (BOOL)tableView:(NSTableView *)tableView acceptDrop:(id<NSDraggingInfo>)info row:(NSInteger)row dropOperation:(NSTableViewDropOperation)dropOperation {
    //    if (_currentlyDraggedObjects == nil || [info draggingSourceOperationMask] == NSDragOperationCopy) {
    //        [self performInsertWithDragInfo:info row:row];
    //    } else {
    //        [tableView beginUpdates];
    //        [self performDragReorderWithDragInfo:info row:row];
    //        [tableView endUpdates];
    
    //    }
    
    
    //if ([[info draggingPasteboard] availableTypeFromArray:[NSArray arrayWithObject:HSONGITEMTYPE]] != nil){

    //}
    

    
    
    id dragSource=[info draggingSource];//拖放源头
    
    //自己不允许拖放
    if (dragSource == self.tableV){
        [self displayTheFocusRingFrame:NO];
        return NSDragOperationNone;
        
    }
//    //如果drag source为songlistView
//    else if (dragSource ==[HMainWC shareWc].songListView.tableV) {
//        
//        
//        
//        
//    }
//    //外面
//    else {
//    
//    
//    }
    
    
    
    NSPasteboard* zPBoard = [info draggingPasteboard];
    
    NSString * zStrAvailableType = [zPBoard availableTypeFromArray:self.supportDragTypesArr];//该方法按顺序返回合适的资源标识符
    
    //添加loading
    [[HMainWC shareWc] addGLoadingReminderWithTitle:nil];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    //如果拖进来的是song实体类 ,那么一定是从歌曲列表拖进来的
    if ([zStrAvailableType compare:HSONGITEMTYPE] == NSOrderedSame ) {

        HPlaylistItem * pitem=nil;
        [[HSQLManager shareSqlMg] openSongDB];//打开数据库
        
        
        //拖到某一行(在不实现排序的前提下可以这样判断,否则用row来判断)
        //这个操作可能会影响播放队列
        if (dropOperation==NSTableViewDropOn) {
            pitem=[self.dataSource objectAtIndex:row];
            [self insertSongsToplaylist:pitem  dragInfo:info];
        }
        //拖到最后(在不实现排序的前提下可以这样判断,否则用row来判断)
        else {

            pitem=[HPlaylistItem defaultItem];
            NSString * defaultname=NSLocalizedString(@"new play list", nil);
            pitem.name=[self getPlayplstNameWithdefaultName:defaultname andIndex:0];

            [self insertPlaylist:pitem dragInfo:info];
        }
        
          [[HSQLManager shareSqlMg] closeSongDB];//关闭数据库
        
    }
    //如果是从外面拖进来
    else if ( UTTypeConformsTo((__bridge CFStringRef)zStrAvailableType, kUTTypeURL)) {
    
    
    NSArray * arr=[info draggingPasteboard].pasteboardItems;
    NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
        __block int handleCount=0;//import count

        [[HSQLManager shareSqlMg] openSongDB];//打开数据库
        
        //循环每一个文件夹
        for (NSPasteboardItem * pasteItem in arr) {
            id item=[pasteItem stringForType:zStrAvailableType];
            
             NSURL *url = [[NSURL alloc] initWithPasteboardPropertyList:item ofType:zStrAvailableType];
            //debugLog(@"dragurl:%@",url.path);
             NSString *typeIdentifier;
          BOOL getsuccess=[url getResourceValue:&typeIdentifier forKey:NSURLTypeIdentifierKey error:NULL];
            
           //  debugLog(@"typeIdentifier is:%@",typeIdentifier);
            if (getsuccess ) {
                
                //如果是文件夹
                if ( [typeIdentifier isEqualToString:(NSString*)kUTTypeFolder]) {
                    //NSString * path=url.path;
                    //debugLog(@"path is:%@",path);

                    [self createPlaylistWithFolderPath:url handelCount:&handleCount];
                    
                }
                //如果是外部拉进来的音乐资源
                else if  ([workspace type:typeIdentifier conformsToType:@"public.audio"]){
               // debugLog(@"this is music url");
                    
                }
 
            }
            /*
            NSString * path=url.path;
          BOOL exist= [[NSFileManager defaultManager] fileExistsAtPath:path];
            
            if (exist) {
                debugLog(@"path is:%@",path);
            } else {
            
            debugLog(@"path not exist");
            }
             */
            
            
            
        }

        [[HSQLManager shareSqlMg] closeSongDB];//关闭数据库

        
        
        //添加
        if (handleCount>0) {
            /*
            NSString * des=[NSString stringWithFormat:@"%@%d%@",NSLocalizedString(@"Successfully import", nil),handleCount,NSLocalizedString(@"items", nil)];
            [[HMainWC shareWc] addAutoRemoveSuccessReminderWithTitle:des];
        */
             }
    
    }
    

     dispatch_async(dispatch_get_main_queue(),^{
    
    //拖完重刷左列表数据
    [[HMainWC shareWc].songListView desselectAllRow];//取消所有选择的行
    [self reloadDataSource];
    

    if (dropOperation==NSTableViewDropOn) {
        [HJAudioPlayer sharePlayer].shouldUpdateQueue=YES;//需要刷新播放列表的话
        [self performSelector:@selector(locationRowAfterimportWithRow:) withObject:[NSString stringWithFormat:@"%d",row] afterDelay:0.1];
    } else {

        //导入后刷新定位播放列表,选中时再高亮[会有问题,所以延时刷新
        [self performSelector:@selector(locationRowAfterimport) withObject:nil afterDelay:0.1];
    }
    
     });
        
        
    });
    
    return YES;
}


#pragma mark  ----------textfield delegate--------


- (void)controlTextDidBeginEditing:(NSNotification *)notification{

    //NSTextField * f=(NSTextField*)[notification object];


}


- (void)controlTextDidEndEditing:(NSNotification *)notification{
    NSTextField * f=(NSTextField*)[notification object];
    f.textColor=[HCoreConfig shareConfig].currentSkinManager.leftListNormalCellTextColor;
    
    //单击和双击,以及右击混用会引起问题,这里统一使用selectrow,禁用右击rename
    NSInteger row=[self.tableV selectedRow];
   // NSInteger crow=[self.tableV clickedRow];
    

    if (row==-1) {
        return;
    }
    
    HPlaylistItem * entity=[self.dataSource objectAtIndex:row];
    //debugLog(@"tag:%d ,value:%@",row,f.stringValue);
    
    if (entity) {
        
        NSTableCellView * selectedCell = [self.tableV  viewAtColumn:0 row:row makeIfNecessary:YES];
      
        
        NSCharacterSet *  whitespaceSet= [NSCharacterSet whitespaceAndNewlineCharacterSet];
        NSString * nTx=[f.stringValue stringByTrimmingCharactersInSet:whitespaceSet];

        
        
        //空串的话用回原来的name
        if ([nTx length]==0) {
            selectedCell.textField.stringValue=CHECKSTR(entity.name);
        }
        
        else {
            
            //没有变化
            if ([entity.name isEqualToString:nTx]) {
                return;
            }
            entity.name=nTx;//更改实体类
            selectedCell.textField.stringValue=nTx;//更改ui

            [HSQLManager updatePlaylistWithItem:entity];
            


            

        }
        
    }

}


#pragma mark  ----------nsmenu delegate--------

- (void)menuNeedsUpdate:(NSMenu*)menu{

    
    //当点击空白行时
    NSUInteger clickrow= [self.tableV clickedRow];
    if (clickrow==-1) {
        return;
    }
    
    
    //分组和几个特殊的不触发某些操作
    
    id item=[self.dataSource objectAtIndex:clickrow];

    BOOL menuDisable=NO;
    if ([item isKindOfClass:[HGroup class]]) {
        menuDisable=YES;
    } else {
    
        HPlaylistItem * pitem=(HPlaylistItem*)item;
        NSString * syncid_m=pitem.syncid;
    
        if ([syncid_m isEqualToString:itunesSyncid ]||[syncid_m isEqualToString:onlineSyncid ] ||[syncid_m isEqualToString:likeSyncid ]  ) {
            menuDisable=YES;
            
        }

    }
    
     NSMenuItem * deleteitem=[self.pTableMenu itemAtIndex:0];

    if (menuDisable==YES) {
       
        [deleteitem setAction:nil];
 
    } else {
    
         [deleteitem setAction:@selector(deleteCertainPlaylist)];

    }
    

}


- (void)menuWillOpen:(NSMenu *)menu {

    //空白行不理会 //group 不理会
 NSUInteger clickrow= [self.tableV clickedRow];
    if (clickrow==-1 || clickrow==0|| clickrow==[self.topGroupArr count]-1) {
        [menu cancelTracking];
    }
    
    
    
    
    

}


- (void)menuDidClose:(NSMenu *)menu {


}



#pragma mark  ----------mouse event--------


@end
